package GameDb;

import GameDb.JDBC.JDBCUtils;
import GameDb.Task.common.DbTask;
import java.sql.Connection;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class DbQueue {
    private static final Queue<DbTask> WAITING_TASK = new ConcurrentLinkedQueue<>();
    private boolean isRunning = true;
    private static int maxWorkThread;
    private final ExecutorService[] workerPool;
    static int taskNum = 0;

    public DbQueue(int num){
        maxWorkThread = num;
        workerPool = new ExecutorService[maxWorkThread];
        startTask();
    }

    public void startTask(){
        if(!isRunning) {
            isRunning = true;
        }
        for(int i=0;i<maxWorkThread;i++){
            workerPool[i] = Executors.newSingleThreadExecutor();
            workerPool[i].execute(new WorkThread());
        }
    }

    public void loadTask(DbTask dbTask){
        if(dbTask !=null) {
            synchronized(this) {
                WAITING_TASK.offer(dbTask);
            }
        }
    }

    public void stopAddTask(){
        isRunning = false;
    }

    private class WorkThread extends Thread{
        public WorkThread(String name){
            super(name);
        }
        public WorkThread(){}
        @Override
        public void run(){
            DbTask task;
            while (isRunning){
                    if (WAITING_TASK.isEmpty()) {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if(!WAITING_TASK.isEmpty()){
                        task = WAITING_TASK.poll();
                    }else{
                        task = null;
                    }

                    try {
                        if (task != null) {
                            Connection conn = new JDBCUtils().getDruidConn();
                            System.out.println("task" + (taskNum++));
                            task.run(conn);
                            System.out.println("等待中的任务数量：" + WAITING_TASK.size());
                        }
                    } catch (Exception e) {
                        System.out.println("task is error");
                        //loadTask(task);
                        e.printStackTrace();
                    }
            }
        }
    }


}
